<?php
/**
 * 会员管理
 *
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */

use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');

class memberControl extends SystemControl{
    const EXPORT_SIZE = 1000;
    public function __construct(){
        parent::__construct();
        Language::read('member');
    }

    public function indexOp() {
        $this->memberOp();
    }

    /**
     * 会员管理
     */
    public function memberOp(){
        Tpl::showpage('member.index');
    }

    /**
     * 会员修改
     */
    public function member_editOp(){
        $lang   = Language::getLangContent();
        $model_member = Model('member');
        /**
         * 保存
         */
        if (chksubmit()){
            /**
             * 验证
             */
            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
            array("input"=>$_POST["member_email"], "require"=>"true", 'validator'=>'Email', "message"=>$lang['member_edit_valid_email']),
            );
            $error = $obj_validate->validate();
            if ($error != ''){
                showMessage($error);
            }else {
                $update_array = array();
                $update_array['member_id']          = intval($_POST['member_id']);
                if (!empty($_POST['member_passwd'])){
                    $update_array['member_passwd'] = md5($_POST['member_passwd']);
                }
                $update_array['member_email']       = $_POST['member_email'];
                $update_array['member_truename']    = $_POST['member_truename'];
                $update_array['member_sex']         = $_POST['member_sex'];
                $update_array['member_qq']          = $_POST['member_qq'];
                $update_array['member_ww']          = $_POST['member_ww'];
                $update_array['member_state']       = $_POST['memberstate'];
                if (!empty($_POST['member_avatar'])){
                    $update_array['member_avatar'] = $_POST['member_avatar'];
                }
                $result = $model_member->editMember(array('member_id'=>intval($_POST['member_id'])),$update_array);
                if ($result){
                    $url = array(
                    array(
                    'url'=>'index.php?act=member&op=member',
                    'msg'=>$lang['member_edit_back_to_list'],
                    ),
                    array(
                    'url'=>'index.php?act=member&op=member_edit&member_id='.intval($_POST['member_id']),
                    'msg'=>$lang['member_edit_again'],
                    ),
                    );
                    $this->log(L('nc_edit,member_index_name').'[ID:'.$_POST['member_id'].']',1);
                    showMessage($lang['member_edit_succ'],$url);
                }else {
                    showMessage($lang['member_edit_fail']);
                }
            }
        }
        $condition['member_id'] = intval($_GET['member_id']);
        $member_array = $model_member->getMemberInfo($condition);

        Tpl::output('member_array',$member_array);
        Tpl::showpage('member.edit');
    }

    /**
     * 新增会员
     */
    public function member_addOp(){
        $lang   = Language::getLangContent();
        $model_member = Model('member');
        /**
         * 保存
         */
        if (chksubmit()){
            /**
             * 验证
             */
            $obj_validate = new Validate();
            $obj_validate->validateparam = array(
                array("input"=>$_POST["member_name"], "require"=>"true", "message"=>$lang['member_add_name_null']),
                array("input"=>$_POST["member_passwd"], "require"=>"true", "message"=>'密码不能为空'),
                array("input"=>$_POST["member_email"], "require"=>"true", 'validator'=>'Email', "message"=>$lang['member_edit_valid_email'])
            );
            $error = $obj_validate->validate();
            if ($error != ''){
                showMessage($error);
            }else {
                $insert_array = array();
                $insert_array['member_name']    = trim($_POST['member_name']);
                $insert_array['member_passwd']  = trim($_POST['member_passwd']);
                $insert_array['member_email']   = trim($_POST['member_email']);
                $insert_array['member_truename']= trim($_POST['member_truename']);
                $insert_array['member_sex']     = trim($_POST['member_sex']);
                $insert_array['member_qq']      = trim($_POST['member_qq']);
                $insert_array['member_ww']      = trim($_POST['member_ww']);
                //默认允许举报商品
                $insert_array['inform_allow']   = '1';
                if (!empty($_POST['member_avatar'])){
                    $insert_array['member_avatar'] = trim($_POST['member_avatar']);
                }

                $result = $model_member->addMember($insert_array);
                if ($result){
                    $url = array(
                    array(
                    'url'=>'index.php?act=member&op=member',
                    'msg'=>$lang['member_add_back_to_list'],
                    ),
                    array(
                    'url'=>'index.php?act=member&op=member_add',
                    'msg'=>$lang['member_add_again'],
                    ),
                    );
                    $this->log(L('nc_add,member_index_name').'[ '.$_POST['member_name'].']',1);
                    showMessage($lang['member_add_succ'],$url);
                }else {
                    showMessage($lang['member_add_fail']);
                }
            }
        }
        Tpl::showpage('member.add');
    }

    /**
     * ajax操作
     */
    public function ajaxOp(){
        switch ($_GET['branch']){
            /**
             * 验证会员是否重复
             */
            case 'check_user_name':
                //检测是否含有敏感词
                $model_setting = Model('setting');
                $sensitive_info = $model_setting->getRowSetting('sensitive_set');
                if ($sensitive_info !== false) {
                    $sensitive_list = @unserialize($sensitive_info['value']);
                }
                if (!is_array($sensitive_list)) {
                    $sensitive_list = array();
                }
                foreach ($sensitive_list as $v) {
                    if($v['name'] == 'member_name'){
                        $is_open = $v['is_open'];
                        break;
                    }
                }
                //开关
                if($is_open == 1 && sensitiveWordDetection($_GET['user_name'])){
                    echo 'false';exit;
                }

                $model_member = Model('member');
                $condition['member_name']   = $_GET['member_name'];
                $condition['member_id'] = array('neq',intval($_GET['member_id']));
                $list = $model_member->getMemberInfo($condition);
                if (empty($list)){
                    echo 'true';exit;
                }else {
                    echo 'false';exit;
                }
                break;
                /**
             * 验证邮件是否重复
             */
            case 'check_email':
                $model_member = Model('member');
                $condition['member_email'] = $_GET['member_email'];
                $condition['member_id'] = array('neq',intval($_GET['member_id']));
                $list = $model_member->getMemberInfo($condition);
                if (empty($list)){
                    echo 'true';exit;
                }else {
                    echo 'false';exit;
                }
                break;
        }
    }

    /**
     * 输出XML数据
     */
    public function get_xmlOp() {
        $model_member = Model('member');
        $member_grade = $model_member->getMemberGradeArr();
        $condition = array();
        if ($_POST['query'] != '') {
            $condition[$_POST['qtype']] = array('like', '%' . $_POST['query'] . '%');
        }
        $order = '';
        $param = array('member_id','member_name','member_avatar','member_email','member_mobile','member_sex','member_truename','member_birthday'
                ,'member_time','member_login_time','member_login_ip','member_points','member_exppoints','member_grade','available_predeposit'
                ,'freeze_predeposit','available_rc_balance','freeze_rc_balance','inform_allow','is_buy','is_allowtalk','member_state'
        );
        if (in_array($_POST['sortname'], $param) && in_array($_POST['sortorder'], array('asc', 'desc'))) {
            $order = $_POST['sortname'] . ' ' . $_POST['sortorder'];
        }
        $page = $_POST['rp'];
        $member_list = $model_member->getMemberList($condition, '*', $page, $order);

        //将会员id全部取出，然后计算会员交易比例
        $member_ids = array_column($member_list, 'member_id');
        if ($member_ids) {
            $model_order = Model('order');
            $field = 'buyer_id,add_time,payment_code,payment_time,finnshed_time,goods_amount,order_amount,shipping_fee,order_state,refund_state,refund_amount,order_type,rpt_amount';
            $map = array(
                'buyer_id' => array('in', $member_ids),
                'order_state' => array('in', [ORDER_STATE_PAY, ORDER_STATE_SEND, ORDER_STATE_SUCCESS]),  //找出所有已经付款的订单
            );
            $member_orders = $model_order->table('orders')->field($field)->where($map)->select();

            $dispose_orders = array();  //处理后的订单数据
            //处理订单数据
            array_walk($member_orders, function($item, $keys) use(&$dispose_orders) {
                //累计成交金额 -- 累计付款金额
                $dispose_orders[$item['buyer_id']]['make_bargain_money'] = isset($dispose_orders[$item['buyer_id']]['make_bargain_money']) ? $dispose_orders[$item['buyer_id']]['make_bargain_money'] : 0;
                $dispose_orders[$item['buyer_id']]['make_bargain_money'] += $item['order_amount'];

                //累计成功金额 -- 累计交易成功金额(订单状态为：已收货，退款状态为：无退款)
                $dispose_orders[$item['buyer_id']]['succeed_money'] = isset($dispose_orders[$item['buyer_id']]['succeed_money']) ? $dispose_orders[$item['buyer_id']]['succeed_money'] : 0;
                if (($item['order_state'] == ORDER_STATE_SUCCESS) && $item['refund_state'] == 0) {
                    $dispose_orders[$item['buyer_id']]['succeed_money'] += $item['order_amount'];
                }

                //累计退款金额
                $dispose_orders[$item['buyer_id']]['refund_money'] = isset($dispose_orders[$item['buyer_id']]['refund_money']) ? $dispose_orders[$item['buyer_id']]['refund_money'] : 0;
                //退款笔数
                $dispose_orders[$item['buyer_id']]['refund_count'] = isset($dispose_orders[$item['buyer_id']]['refund_count']) ? $dispose_orders[$item['buyer_id']]['refund_count'] : 0;
                if ($item['refund_state'] != 0) {
                    $dispose_orders[$item['buyer_id']]['refund_money'] += $item['refund_amount'];
                    $dispose_orders[$item['buyer_id']]['refund_count'] += 1;
                }

                //订单笔数
                $dispose_orders[$item['buyer_id']]['order_count'] = isset($dispose_orders[$item['buyer_id']]['order_count']) ? $dispose_orders[$item['buyer_id']]['order_count'] : 0;
                $dispose_orders[$item['buyer_id']]['order_count'] += 1;

                //成交次数 -- 付款次数
                $dispose_orders[$item['buyer_id']]['make_bargain_time'] = isset($dispose_orders[$item['buyer_id']]['make_bargain_time']) ? $dispose_orders[$item['buyer_id']]['make_bargain_time'] : 0;
                $dispose_orders[$item['buyer_id']]['make_bargain_time'] += 1;

                //最后下单时间
                $finally_order_time = isset($dispose_orders[$item['buyer_id']]['finally_order_time']) ? $dispose_orders[$item['buyer_id']]['finally_order_time'] : 0;
                $dispose_orders[$item['buyer_id']]['finally_order_time'] = ($finally_order_time > $item['add_time']) ? $finally_order_time : $item['add_time'];
                
                //退款比例 -- 成功申请退款笔数/全部付款订单数*100%
                $dispose_orders[$item['buyer_id']]['refund_ratio'] = $dispose_orders[$item['buyer_id']]['refund_count'] / $dispose_orders[$item['buyer_id']]['make_bargain_time'];
                $dispose_orders[$item['buyer_id']]['refund_ratio'] = sprintf("%.2f", $dispose_orders[$item['buyer_id']]['refund_ratio']);
            });
        }

        $sex_array = $this->get_sex();

        $data = array();
        $data['now_page'] = $model_member->shownowpage();
        $data['total_num'] = $model_member->gettotalnum();

        foreach ($member_list as $value) {
            $param = array();
            $param['operation'] = "<a class='btn blue' href='index.php?act=member&op=member_edit&member_id=" . $value['member_id'] . "'><i class='fa fa-pencil-square-o'></i>编辑</a>";
            $param['member_id'] = $value['member_id'];
            $param['member_name'] = "<img src=".getMemberAvatarForID($value['member_id'])." class='user-avatar' onMouseOut='toolTip()' onMouseOver='toolTip(\"<img src=".getMemberAvatarForID($value['member_id']).">\")'>".$value['member_name'];
            $param['member_mobile'] = encryptShow($value['member_mobile'], 4, 4);

            $param['make_bargain_money'] = isset($dispose_orders[$param['member_id']]['make_bargain_money']) ? $dispose_orders[$param['member_id']]['make_bargain_money'] : null;
            $param['succeed_money'] = isset($dispose_orders[$param['member_id']]['succeed_money']) ? $dispose_orders[$param['member_id']]['succeed_money'] : null;
            $param['refund_money'] = isset($dispose_orders[$param['member_id']]['refund_money']) ? $dispose_orders[$param['member_id']]['refund_money'] : null;
            $param['refund_ratio'] = isset($dispose_orders[$param['member_id']]['refund_ratio']) ? $dispose_orders[$param['member_id']]['refund_ratio'] : null;
            $param['make_bargain_time'] = isset($dispose_orders[$param['member_id']]['make_bargain_time']) ? $dispose_orders[$param['member_id']]['make_bargain_time'] : null;

            $param['member_login_time'] = date('Y-m-d H:i:s', $value['member_login_time']);
            $param['finally_order_time'] = isset($dispose_orders[$param['member_id']]['finally_order_time']) ? date('Y-m-d H:i:s', $dispose_orders[$param['member_id']]['finally_order_time']) : null;            
            
            $param['member_state'] = $value['member_state'] ==  '1' ? '<span class="yes"><i class="fa fa-check-circle"></i>是</span>' : '<span class="no"><i class="fa fa-ban"></i>否</span>';
            $data['list'][$value['member_id']] = $param;
        }
        echo Tpl::flexigridXML($data);exit();
    }

    /**
     * 性别
     * @return multitype:string
     */
    private function get_sex() {
        $array = array();
        $array[1] = '男';
        $array[2] = '女';
        $array[3] = '保密';
        return $array;
    }
    /**
     * csv导出
     */
    public function export_csvOp() {
        $model_member = Model('member');
        $condition = array();
        $limit = false;
        if ($_GET['id'] != '') {
            $id_array = explode(',', $_GET['id']);
            $condition['member_id'] = array('in', $id_array);
        }
        if ($_GET['query'] != '') {
            $condition[$_GET['qtype']] = array('like', '%' . $_GET['query'] . '%');
        }
        $order = '';
        $param = array('member_id','member_name','member_avatar','member_email','member_mobile','member_sex','member_truename','member_birthday'
                ,'member_time','member_login_time','member_login_ip','member_points','member_exppoints','member_grade','available_predeposit'
                ,'freeze_predeposit','available_rc_balance','freeze_rc_balance','inform_allow','is_buy','is_allowtalk','member_state'
        );
        if (in_array($_GET['sortname'], $param) && in_array($_GET['sortorder'], array('asc', 'desc'))) {
            $order = $_GET['sortname'] . ' ' . $_GET['sortorder'];
        }
        if (!is_numeric($_GET['curpage'])){
            $count = $model_member->getMemberCount($condition);
            if ($count > self::EXPORT_SIZE ){   //显示下载链接
                $array = array();
                $page = ceil($count/self::EXPORT_SIZE);
                for ($i=1;$i<=$page;$i++){
                    $limit1 = ($i-1)*self::EXPORT_SIZE + 1;
                    $limit2 = $i*self::EXPORT_SIZE > $count ? $count : $i*self::EXPORT_SIZE;
                    $array[$i] = $limit1.' ~ '.$limit2 ;
                }
                Tpl::output('list',$array);
                Tpl::output('murl','index.php?act=member&op=index');
                Tpl::showpage('export.excel');
                exit();
            }
        } else {
            $limit1 = ($_GET['curpage']-1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $limit = $limit1 .','. $limit2;
        }

        $member_list = $model_member->getMemberList($condition, '*', null, $order, $limit);
        $this->createCsv($member_list);
    }
    /**
     * 生成csv文件
     */
    private function createCsv($member_list) {
        $model_member = Model('member');
        $member_grade = $model_member->getMemberGradeArr();
        // 性别
        $sex_array = $this->get_sex();
        $data = array();
        foreach ($member_list as $value) {
            $param = array();
            $param['member_id'] = $value['member_id'];
            $param['member_name'] = $value['member_name'];
            $param['member_avatar'] = getMemberAvatarForID($value['member_id']);
            $param['member_email'] = $value['member_email'];
            $param['member_mobile'] = $value['member_mobile'];
            $param['member_sex'] = $sex_array[$value['member_sex']];
            $param['member_truename'] = $value['member_truename'];
            $param['member_birthday'] = $value['member_birthday'];
            $param['member_time'] = date('Y-m-d', $value['member_time']);
            $param['member_login_time'] = date('Y-m-d', $value['member_login_time']);
            $param['member_login_ip'] = $value['member_login_ip'];
            $data[$value['member_id']] = $param;
        }

        $header = array(
                'member_id' => '会员ID',
                'member_name' => '会员名称',
                'member_avatar' => '会员头像',
                'member_email' => '会员邮箱',
                'member_mobile' => '会员手机',
                'member_sex' => '会员性别',
                'member_truename' => '真实姓名',
                'member_birthday' => '出生日期',
                'member_time' => '注册时间',
                'member_login_time' => '最后登录时间',
                'member_login_ip' => '最后登录IP'
        );
        \Shopnc\Lib::exporter()->output('member_list' .$_GET['curpage'] . '-'.date('Y-m-d'), $data, $header);
    }
}
